# Create your views here.
import logging
import random

from django.http import HttpResponse
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView

from celery_tasks.sms.tasks import send_sms_code
from mall.libs.captcha.captcha import captcha
from django_redis import get_redis_connection

from mall.utils.yuntongxun.sms import CCP
from verifications.serializers import CheckImageCodeSerializer
from . import constants


logger = logging.getLogger('django')


class ImageCodeView(APIView):
    """图片验证码"""
    authentication_classes = []
    permission_classes = []
    def get(self, request, image_code_id):
        # 生成验证码图片
        text, image = captcha.generate_captcha()
        # 保存真实值
        redis_connection = get_redis_connection('verify_codes')
        redis_connection.setex('img_{}'.format(image_code_id), constants.IMAGE_CODE_REDIS_EXPIRES, text)
        # 返回图片
        return HttpResponse(image, content_type='image/jpg')


# GET /sms_codes/(?P<mobile>1[3456789]\d{9})/$?image_code_id=xxx&text=xxx
class SmsCodeView(GenericAPIView):
    """短信验证码"""
    serializer_class = CheckImageCodeSerializer
    def get(self, request, mobile):
        # 校验参数
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 生成短信验证码
        sms_code = '{:0>6d}'.format(random.randint(0, 999999))
        # 保存真实值和用户60秒内发送记录到数据库
        redis_connection = get_redis_connection('verify_codes')
        pl = redis_connection.pipeline()
        pl.setex('sms_code_{}'.format(mobile), constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_{}'.format(mobile), constants.SMS_CODE_SEND_FLAG_REDIS_EXPIRES, 1)
        pl.execute()
        # 发送短信
        # try:
        #     ccp = CCP()
        #     expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        #     result = ccp.send_template_sms(mobile, [sms_code, expires], constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error("发送短信验证码[异常][ mobile: {}, message: {}]".format(mobile, e))
        #     return Response({'message: failed'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        #     if result == 0:
        #         logger.info("发送短信验证码[正常][mobile: {} ]".format(mobile))
        #         return Response({'message: OK'})
        #     else:
        #         logger.warning("发送短信验证码[失败][mobile: {} ]".format(mobile))
        #         return Response({'message: failed'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # 使用celery发送短信验证码
        expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        send_sms_code.delay(mobile, sms_code, expires, constants.SMS_CODE_TEMP_ID)
        print(mobile, sms_code, expires, constants.SMS_CODE_TEMP_ID)

        # 返回响应
        return Response({'message: OK'})
